
// pinia
import {
    storeToRefs
} from 'pinia'
import {
    useUserStore
} from "@/stores/useUserStore.js"

// 获取pinia的数据
const userStore = useUserStore()

// 从pinia的数据中结构出值并做响应式
const {
    token
} = storeToRefs(userStore)


const request = (config = {}) => {
    let {
        url,
        data = {},
        method = "GET",
        header = {},
        needStringify = false,   //是否需要序列化
        isErrMsg = true,      //是否需要错误提示
    } = config

    if (needStringify) {
        data = JSON.stringify(data)
    }

    // 存在token的时候
    if (token.value) {
        header['Authorization'] = 'bearer ' + token.value
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url,
            data,
            method,
            header,
            success: res => {
                if (res.statusCode === 401) {
                    uni.showToast({
                        title: "请登录后进行操作",
                        icon: "none",
                        success: () => {
                            setTimeout(() => {
                                uni.navigateTo({
                                    url: '/pages/login/login'
                                })
                            }, 500)
                        }
                    })
                    return
                }

                if (res.data.code === 0) {
                    resolve(res.data)
                } else {
                    if (isErrMsg) {
                        uni.showModal({
                            title: "错误提示",
                            content: res.data.msg,
                            showCancel: false,
                            confirmColor: '#000'
                        })
                        reject(res.data)

                    } else {
                        resolve(res.data)
                    }
                }
            },
            fail: err => {
                reject(err)
            }
        })
    })
}

const comm_request = (config = {}) => {
    let {
        url,
        data = {},
        method = "GET",
        header = {},
        needStringify = false,   //是否需要序列化
        isErrMsg = true,      //是否需要错误提示
    } = config

    if (needStringify) {
        data = JSON.stringify(data)
    }

    return new Promise((resolve, reject) => {
        uni.request({
            url,
            data,
            method,
            header,
            success: res => {
                if (res.statusCode === 200) {
                    resolve(res.data)
                }else{
					reject(null)
				}
            },
            fail: err => {
                reject(err)
            }
        })
    })
}


export { request, comm_request }